<template>
	<view>
		<u-navbar title="充电车辆" :autoBack="false" @leftClick="back">
			<template #right>
				<view style="display: flex;align-items: center;color: #2093f5;height: 100%;" @click="init()">
					<text class="iconfont icon-shuaxin" style="margin-right: 10rpx;"></text>
					{{$z.$t("刷新")}}{{sxtime}}
				</view>
			</template>
		</u-navbar>
		<view v-if="item">
			<view class="pcs">{{$z.$t("站点")}}：{{ item.pcs }}</view>
			<view class="item-time" v-if='item.b_yy == 1'>
				<view class="box">
					<view class="title">开始充电</view>
					<view class="value"> <span
							v-if=" item.startTimeObj && item.startTimeObj.prefix">{{ item.startTimeObj.prefix }}</span>
						{{ item.startTimeObj.time }}
					</view>
				</view>
				<view class="box">
					<view class="title">结束充电</view>
					<view class="value">
						<span v-if="item.endTimeObj &&  item.endTimeObj.prefix">{{ item.endTimeObj.prefix }}</span>
						{{ item.endTimeObj.time }}
					</view>
				</view>
			</view>
			<view class="soc">
				<view class="soc1">{{ item.td }}</view>
				<template v-if="item.xtype==8">
					<view class="soc2">{{ item.b_grcd }}%</view>
					<view class="soc3">SOC</view>
				</template>
				<view class="" v-else style="padding-bottom: 40rpx;">
					<u--image
						src="http://img.gpsserver.cn:20080/240506/050613501517149_240506135015_2jJEBiCmbsC8ZGssBN64ewGwjd6mCRdG.png"
						height="48.2" width="115.8" mode="heightFix"></u--image>
				</view>

				<!-- -->
			</view>
			<!-- zsc -->
			<view class="gtel">{{$z.$t("设备ID")}}:{{ item.gtel }}</view>
			<view class="zsc" v-if="item.zsc">
				{{$z.$t("预计充满时长")}}:{{item.zsc}}
			</view>
			<view class="list">
				<view class="item">
					<view class="iconfont icon-dianliang"></view>
					<view class="value">{{ item.dl }}</view>
					<view class="label">{{$z.$t("已充电量(度)")}}</view>
				</view>
				<view class="item">
					<view class="iconfont icon-31shijian"></view>
					<view class="value">{{ item.cdsc }}</view>
					<view class="label">{{$z.$t("已充时长")}}</view>
				</view>
				<view class="item">
					<view class="iconfont icon-chongzhi"></view>
					<view class="value">{{ item.je }}</view>
					<view class="label">{{$z.$t("已充金额(元)")}}</view>
				</view>
				<view class="item">
					<view class="iconfont icon-dianya"></view>
					<view class="value">{{ item.cdu }}</view>
					<view class="label">{{$z.$t("实时电压")}}</view>
				</view>
				<view class="item">
					<view class="iconfont icon-dianliu"></view>
					<view class="value">{{ item.cdi }}</view>
					<view class="label">{{$z.$t("实时电流")}}</view>
				</view>
				<view class="item">
					<view class="iconfont icon-gongshuai"></view>
					<view class="value">{{ item.cdp }}</view>
					<view class="label">{{$z.$t("实时功率")}}</view>
				</view>
			</view>
			<view style="padding: 30rpx 20rpx">
				<u-button class="btn" size="medium" type="primary" @click="CcdSJEnd(item)"
					v-if="item.b_end != 1 && item.b_cd == 1">
					{{CcdSJEnddatas[item.ddh]?$z.$t("正在断电"):$z.$t("结束充电")}}
				</u-button>
			</view>
			<!-- <view style="padding: 30rpx 20rpx" v-else>
				<u-button class="btn" size="medium" type="primary" @click="CcdSJEnd(item)"
					v-if="item.b_end != 1 && item.b_cd == 1 && !isAppointmentPassed(item.sjyye)">
					{{CcdSJEnddatas[item.ddh]?$z.$t("正在断电"):$z.$t("结束充电")}}
				</u-button>
			</view> -->
		</view>
		<fixedbtn v-if="item && item.b_yy == 1 && isAppointmentPassed(item.sjyys) && item.b_end == 0">
			<u-button type="primary" @click="handleChargeCancal(item)">取消预约充电</u-button>
		</fixedbtn>
		<zmodal ref="zmodal"></zmodal>

	</view>
</template>

<script>
	import config from "@/config/index.js"
	import qs from "qs"
	export default {
		data() {
			return {
				ChargeUser: {},
				query: {},
				sxsj: 15,
				sxtime: 15,
				sxtieminterval: "",
				gtel: '',
				unfinishedOrder: {},
				isparkingLock: '',
			};
		},
		asyncComputed: {
			async item() {
				if (!this.ChargeUser.gtel) {
					return {}
				}
				let r = [];
				let abc = [
					"A",
					"B",
					"C",
					"D",
					"E",
					"F",
					"G",
					"H",
					"I",
					"J",
					"K",
					"L",
					"M",
					"N",
				];
				// for (let i = 0; i < this.ChargeUser.length; i++) {
				let item = this.ChargeUser;
				let p = {
					...item,

				};
				let ChargeCarSys = await this.$store.dispatch("request/getRequest", {
					url: "/ChargeCarSys",
					data: {
						gtel: item.gtel,
					},
				});
				ChargeCarSys = ChargeCarSys[0] || {};
				let gtel = await this.$store.dispatch("request/getRequest", {
					url: "/gtel",
					data: {
						gtel: item.gtel,
					},
				});
				gtel = gtel[0] || {};
				ChargeCarSys = {
					...ChargeCarSys,
					...gtel
				}


				let StationCar = await this.$store.dispatch("request/getRequest", {
					url: "/Station",
					data: {
						id: ChargeCarSys.pcs,
					},
				});
				console.log('item123', item)
				StationCar = StationCar[0] || {};
				if (item.sjyys) {
					let GetRfChargeuserCarYY = await this.$z.request("/GetRfChargeuserCarYY", {
						ddh: item.ddh
					});
					GetRfChargeuserCarYY = GetRfChargeuserCarYY[0]
					p.startTimeObj = this.formatTimeDisplay(GetRfChargeuserCarYY.sjyys);
					p.endTimeObj = this.formatTimeDisplay(GetRfChargeuserCarYY.sjyye);

				}
				p.pcs = StationCar.pcs || "";
				p.tdz = item.td;
				p.td = `${abc[item.td - 1]}枪`;
				p.b_grcd = item.b_grcd;
				p.gtel = item.gtel;
				p.xtype = ChargeCarSys.xtype;
				p.dl = Math.ceil(item.dl / 100) / 100;

				let cdsc = this.$z.timefn.getUTCtimeceil(
					item.sjcds || "",
					item.sjcde || "", 1
				);
				if (cdsc <= 0) {
					cdsc = 0;
				}
				if (ChargeCarSys.xtype == '8' && cdsc != 0) {
					let soc1 = Number(p.endzt) || 0;
					let soc2 = Number(p.b_grcd) || 0;
					let zsc = cdsc / (soc2 - soc1) * (100 - soc2)
					zsc = parseInt(zsc / 60)
					console.log(zsc, soc2 - soc1, "soc2");
					if (zsc != 0 && soc2 - soc1 > 0) {
						let h = parseInt(zsc / 60);
						let m = zsc % 60;
						if (h < 10) {
							h = "0" + h;
						}
						if (m < 10) {
							m = "0" + m;
						}
						p.zsc = `${h}:${m}`;
					}
				}

				// js把cdsc转换成时间00:00
				cdsc = parseInt(cdsc / 60)
				let h = parseInt(cdsc / 60);
				let m = cdsc % 60;
				if (h < 10) {
					h = "0" + h;
				}
				if (m < 10) {
					m = "0" + m;
				}
				p.cdsc = `${h}:${m}`;
				if (ChargeCarSys.b_ask == 0) {
					let cdu = 220
					let cdi = Number(item.cddl) / 100
					p.cdu = cdu; //电压
					p.cdi = cdi; //电流
					p.cdp = cdu.mul(cdi); //功率
				} else if (ChargeCarSys.gtype == 2) {
					let cdu = 220
					let cdp = (Number(item.cddl)).toFixed(1)
					p.cdu = cdu; //电压
					p.cdp = cdp; //功率
					p.cdi = Math.ceil(cdp / cdu * 10) / 10; //电流
				} else {
					// / 10 
					let cdu = Number(item.ycglcs) / 10 || 0;
					let cdp = Number(item.ycglcss) / 10 || 0;
					if (cdu == "0") {
						cdu = 220
					}
					if (ChargeCarSys.gtype == "61") {
						p.cdu = cdu; //电压
						p.cdp = cdp; //功率
						p.cdi = Math.ceil((cdp / cdu) * 100) / 100; //电流
						if (!p.cdi || cdp == 0 || cdu == 0) {
							p.cdi = 0;
						}
					} else {
						cdu = Number(item.ycglcs) || 0;
						if (cdu == "0") {
							cdu = 220
						}
						let cdi = this.dqdlfn({
							...p,
							ChargeCar: ChargeCarSys
						})
						cdp = cdu.mul(cdi)
						// 功率
						p.cdu = cdu; //电压
						p.cdp = cdp; //功率
						p.cdi = cdi; //电流
					}

				}

				p.cdp = Math.ceil(p.cdp / 10) / 100
				p.ddh = item.ddh
				p.je = Number(item.je) / 100;
				r.push(p);
				// }
				console.log('r[0]', r[0])
				return r[0] || {};
			},
		},
		// mounted() {
		// 	this.init();
		// 	// 30
		// },
		onLoad(query) {
			this.query = query;
			this.$store.dispatch("user/getuser");
			this.gtel = query.gtel
			this.isparkingLock = query.isparkingLock

			console.log(query.gtel, "query");
		},
		computed: {
			CcdSJEnddatas() {
				return this.$store.state.config.CcdSJEnddatas
			},

		},
		beforeDestroy() {
			clearInterval(this.sxtieminterval);
		},
		onHide() {
			clearInterval(this.sxtieminterval);
		},
		onShow() {
			this.init();
			//isparkingLock
		},
		methods: {
			formatTimeDisplay(dateString) {
				if (!dateString) return {
					prefix: '',
					time: ''
				};

				const date = new Date(dateString);
				const now = new Date();
				const oneDay = 24 * 60 * 60 * 1000;

				// 计算日期差
				const diffDays = Math.round((date - now) / oneDay);

				// 格式化时间部分 (HH:mm)
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				const timeStr = `${hours}:${minutes}`;

				// 根据日期关系返回前缀
				if (diffDays === 0) {
					return {
						prefix: '',
						time: timeStr
					}; // 当天
				} else if (diffDays === 1) {
					return {
						prefix: '次日',
						time: timeStr
					}; // 次日
				} else {
					// 其他日期 (MM-dd)
					const month = (date.getMonth() + 1).toString().padStart(2, '0');
					const day = date.getDate().toString().padStart(2, '0');
					return {
						prefix: `${month}-${day}`,
						time: timeStr
					};
				}
			},
			isAppointmentPassed(sjyys) {
				if (!sjyys) return false;
				try {
					const appointmentTime = new Date(sjyys).getTime();
					console.log('appointmentTime', appointmentTime, Date.now())
					return appointmentTime > Date.now();
				} catch (e) {
					return false;
				}
			},
			async handleChargeCancal(val) {
				let par = await this.$z.request('/CcdJEtk', {
					ddh: val.ddh,
				})
				if (par[0].par == 'succeed') {
					this.$refs.zmodal.init({
						title: '提示',
						content: '操作成功',
						confirm: () => {
							this.$z.back()
						}
					})
				} else {
					uni.showToast({
						title: '操作失败',
						icon: 'none'
					});
				}
			},
			async back() {
				let ChargeUser = await this.$z.request("/ChargeUser");
				// const chargeOrderGtel = ChargeUser.find(item => item.b_end == 0);
				let ChargeCarSys = await this.$z.request("/ChargeCarSys", {
					gtel: this.item.gtel,
				});
				ChargeCarSys = ChargeCarSys[0]
				console.log('ChargeCarSys.type', ChargeCarSys.type);
				if (ChargeCarSys.type == 14) {
					uni.navigateTo({
						url: `/pages/order/order`,
					});
				} else {
					this.$z.back();
				}

			},
			dqdlfn(p) {
				console.log(p, "pp");
				if (!p.gtel) {
					return 0;
				}
				let ChargeCar = p.ChargeCar;
				if (ChargeCar.b_ask == 1 && [61, 62].indexOf(Number(ChargeCar.gtype)) < 0) {
					let dl = p.cddl / 220 * 100;
					return parseInt(dl) / 100;
				} else {
					return Number(p.cddl) / 100;
				}
			},
			sxfn() {
				// 清除旧的定时器（如果存在）
				if (this.sxtieminterval) {
					clearInterval(this.sxtieminterval);
				}

				// 初始化倒计时时间
				this.sxtime = parseInt(this.sxsj);
				// clearInterval(this.sxtieminterval);
				this.sxtieminterval = setInterval(() => {
					this.sxtime--;
					if (this.sxtime <= 0) {

						this.init()
					}
				}, 1000)
			},
			async init() {
				// if (!this.$store.state.user.USearch.uUser) {
				// 	await
				// }
				clearInterval(this.sxtieminterval);
				let ChargeUser = await this.$z.request("/ChargeUser");

				if (this.query.gtel) {
					this.ChargeUser = ChargeUser.find(e => {
						return e.gtel == this.query.gtel && e.td === this.query.td;
					}) || {}

				} else {

					this.ChargeUser = ChargeUser[0] || {};
				}
				if (!this.ChargeUser.gtel) {
					this.$refs.zmodal.init({
						content: this.$z.$t("没有充电记录"),
						confirm: () => {
							this.$z.back()
						}
					})
				}
				this.sxfn()
			},
			async GetRfCDfn() {
				let par = await this.$z.request('/GetRfCD', {
					csta: 0,
					cmax: 1,
					uUser: this.$store.state.user.USearch.uUser
				})
				// 
				if (par.length == 1 && par[0].b_end == 1) {
					uni.hideLoading();
					uni.navigateTo({
						url: `/pages/order/ddxq/ddxq?${qs.stringify(par[0])}`
					})
				} else {
					setTimeout(() => {
						this.GetRfCDfn()
					}, 1000)
				}
			},
			CcdSJEnd(p) {
				if (this.CcdSJEnddatas[p.ddh]) {
					uni.showToast({
						title: this.$z.$t('正在结束充电中'),
						icon: "none"
					});
					return;
				}
				this.$refs.zmodal.init({
					content: this.$z.$t("退款将不再为您提供电量，确认？"),
					showcancel: true,
					confirm: async () => {
						let par = await uni.$z.request("/CcdSJEnd", {
							gtel: p.gtel,
							td: p.tdz
						})
						this.$store.commit("config/setCcdSJEnddatas", p.ddh)
						if (par[0].par == "succeed") {
							uni.showToast({
								title: this.$z.$t('操作成功'),
								icon: "none"
							});
							uni.showLoading({
								title: '加载中'
							});
							this.GetRfCDfn()

						} else {
							let str = config.pars[par[0]] ? config.pars[par[0]] : this.$z.$t("未知错误")
							uni.showToast({
								title: str,
								icon: "none"
							});
							setTimeout(function() {
								uni.redirectTo({
									url: '/pages/ChargeUser/ChargeUser'
								});
							}, 500)
						}
					}
				})

			},

		},
	};
</script>

<style lang="scss">
	page {
		background: #f4f7f8;
	}

	.pcs {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		padding: 32rpx 0;
	}

	.item-time {
		display: flex;
		justify-content: space-between;
		background-color: #fff;
		padding: 20rpx 40rpx;
		border-radius: 20rpx;
		margin: 0 140rpx;
		margin-bottom: 20rpx;

		.box {

			.title {
				color: #6d6f74;
				margin-bottom: 20rpx;
			}

			.value {
				font-size: 36rpx;
				font-weight: 600;
			}

			span {
				font-size: 28rpx;
				font-weight: 600;
				color: #6d6f74;
			}
		}
	}

	.soc {
		height: 456rpx;
		background-image: url("@/static/ChargeUser/soc.png");
		background-size: 456rpx 456rpx;
		background-repeat: no-repeat;
		background-position: center;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;
		padding: 100rpx 0;

		.soc1 {
			font-size: 50rpx;
			font-weight: bold;
			color: #2093f5;
		}

		.soc2 {
			font-size: 56rpx;
			font-weight: bold;
			color: #333333;
		}

		.soc3 {
			font-size: 48rpx;
			font-weight: bold;
			color: #787878;
		}
	}

	.zsc {
		font-size: 28rpx;
		color: $uni-color-primary;
		text-align: center;
		// line-height: 20rpx;
		position: relative;
		top: -30rpx;
	}

	.gtel {
		font-size: 24RPX;
		color: $uni-text-color-grey;
		text-align: center;
		padding: 28rpx 0 50rpx 0;
	}

	.list {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		padding: 0 20rpx;

		.item {
			width: 210rpx;
			height: 230rpx;
			background: #fff;
			border-radius: 20rpx;
			margin-top: 20rpx;
			padding: 40rpx 0;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			align-items: center;

			.iconfont {
				font-size: 48rpx;
				font-weight: bold;
				color: #333;
			}

			.label {
				font-size: 24rpx;
			}

			.value {
				font-size: 28rpx;
				font-weight: bold;
				color: #333;
			}
		}
	}
</style>